package cd.cdyb.sms.controller.base;

import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author Junpeng.Su
 * @create 2017-07-14 上午 11:01
 * @description
 */
@Order(99)
@RestControllerAdvice
public class ResultResponseBodyController implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Class returnType = methodParameter.getMethod().getReturnType();
        if (void.class.isAssignableFrom(returnType)) {
            return new SimpleVo("empty");
        } else if (Object.class.equals(returnType)) {
            return o;
        } else if (returnType.isPrimitive() || SimpleVo.class.isAssignableFrom(returnType)) {
            return o;
        }
        return new SimpleVo(o);
    }
}
